package com.webwork.lims.transport.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.webwork.lims.transport.dao.TransDao;
import com.webwork.lims.transport.dataobject.TransOrder;
import com.webwork.lims.transport.dataobject.Ways;
import com.webwork.lims.transport.service.TransService;
import com.webwork.lims.transport.service.WaysService;
import com.webwork.lims.util.Paging;

@Service
public class TransServiceImpl implements TransService {

	@Autowired
	private TransDao transDao;
	
	@Autowired
	private WaysService waySve;
	
	@Override
	public int count(TransOrder queryObj) {
		return transDao.count(queryObj);
	}

	@Override
	public List<TransOrder> query(TransOrder queryObj) {
		return this.query(queryObj, new Paging(0, 0));
	}
	
	@Override
	public List<TransOrder> query(TransOrder queryObj, Paging paging) {
		return transDao.query(queryObj, paging.getCurrPage(), paging.getPageSize());
	}

	@Override
	public TransOrder get(String transId) {
		TransOrder queryObj = new TransOrder();
		queryObj.setTransId(transId);
		List<TransOrder> order = this.query(queryObj);
		if (order != null && order.size() > 0) {
			if (order.size() > 1) {
				System.out.println("存在不止一条记录!");
			} else {
				return order.get(0);
			}
		} else {
			System.out.println("找不到该出库单!");
		}
		return null;
	}

	@Override
	public void save(TransOrder order) {
		if (this.get(order.getTransId()) != null) {
			this.update(order);
		} else {
			this.insert(order);
		}
	}

	@Override
	public void insert(TransOrder order) {
		transDao.insert(order);
	}

	@Override
	public void update(TransOrder order) {
		transDao.update(order);
	}

	@Override
	public String getWayLine(int zoneCode) {
		String ret = "";
		ret = this.getZone(zoneCode + "", zoneCode);
		return ret;
	}
	
	/**
	 * 递归查找路线
	 * (未解决问题:若有多条线路如何解决)
	 * @param str
	 * @param zoneCode
	 * @return
	 */
	private String getZone(String str, int zoneCode) {
		if (zoneCode != 1) {
			Ways queryObj = new Ways();
			queryObj.setEndCode(zoneCode);
			List<Ways> ways = waySve.query(queryObj);
			if (ways.size() > 0) {
				for (Ways way : ways) {
					str = way.getStartCode() + "-" + str;
					str = this.getZone(str, way.getStartCode());
				}
			} else {
				return "";
			}
		}
		return str;
	}
	
}
